import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';

const service = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_API,
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 注入token;
    const {access_token} = useUserStore();
    if (access_token) {
      // 如果存在token则注入token
      config.headers.Authorization = access_token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response.data;
    } else {
      ElMessage.error(response.statusText);
      return Promise.reject(new Error(response.statusText));
    }
  },
  (error) => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error);
  }
);

export default service;


